import "./index.less";
import React, { useState, useEffect } from "react";
import { Modal } from "antd";
import type { ColumnsType } from "antd/es/table";
import FileList from "../FileList/index";
import { downloadByUrl } from "@/utils/file/download";
import { useTranslation } from "react-i18next";
import { isArray } from "@/utils/is";
import { createPreviewActionColumn, createPreviewColumns } from "../data";

interface PreviewFileItem {
	url: string;
	type?: string;
	name?: string;
}

interface Props {
	value: string[];
	onListChange?: (urls: string[]) => void;
	onDelete?: (url: string) => void;
}

const UploadPreviewModal: React.FC<Props> = ({ value, onListChange, onDelete }) => {
	const [fileList, setFileList] = useState<PreviewFileItem[]>([]);
	const { t } = useTranslation();
	const columns = createPreviewColumns() as ColumnsType<PreviewFileItem>;
	useEffect(() => {
		if (!isArray(value)) {
			setFileList([]);
			return;
		}

		const formattedFiles = value
			.filter(item => !!item)
			.map(item => ({
				url: item,
				type: item.split(".").pop() || "",
				name: item.split("/").pop() || ""
			}));

		setFileList(formattedFiles);
	}, [value]);

	const handleRemove = (record: PreviewFileItem) => {
		const updatedFileList = fileList.filter(item => item.url !== record.url);
		setFileList(updatedFileList);
		onDelete?.(record.url);
		onListChange?.(updatedFileList.map(item => item.url));
	};

	const handleDownload = (record: PreviewFileItem) => {
		const { url = "" } = record;
		downloadByUrl({ url });
	};
	const actionColumn = createPreviewActionColumn({ handleRemove, handleDownload });
	return (
		<Modal
			title={t("component.upload.preview")}
			width={800}
			visible
			className="upload-preview-modal"
			footer={null} // Hide default footer buttons
		>
			<FileList dataSource={fileList} columns={columns} actionColumn={actionColumn} />
		</Modal>
	);
};

export default UploadPreviewModal;
